package com.ms.game.itembox.container;

import java.util.ArrayList;

import org.hibernate.Query;
import org.hibernate.Session;

import com.ms.game.db.dto.DataTransfer;
import com.ms.game.itembox.ChangeItem;
import com.ms.game.itembox.ChangeItemLister;
import com.ms.game.itembox.Item;
import com.ms.game.itembox.ItemBox;
import com.ms.game.itembox.ItemChangeParam;
import com.ms.game.itembox.ItemChangeWay;
import com.ms.game.itembox.ItemStatus;
import com.ms.game.itembox.db.PlayerItemChangeLogModel;
import com.ms.game.itembox.db.PlayerItemModel;
import com.ms.game.itembox.db.TreasureBoxChangeLogModel;
import com.ms.game.itembox.db.UpdateLastLevelBoxUseLevelAsync;
import com.ms.game.itembox.message.SBroadCastGetItems;
import com.ms.game.itembox.message.SSimpleItem;
import com.ms.player.Player;
import com.ms.service.error.ErrorCode;
import com.ms.service.module.analysisgroup.ItemCountWay;
import com.ms.service.module.analysisgroup.db.model.ItemChangeCountModel;
import com.ms.service.module.zone.BasicZone;
import com.ms.service.module.zone.module.BasicZoneModule;
import com.xpec.c4.db.hibernate.manager.HibernateAnalysisManager;
import com.xpec.c4.db.hibernate.manager.HibernateLogManager;
import com.xpec.c4.db.hibernate.manager.HibernateManager;
import com.xpec.c4.db.model.PlayerModel;
import com.xpec.c4.game.datamanager.BaseDataInfo;
import com.xpec.c4.game.system.InitData;
import com.xpec.c4.game.utility.GUID;
import com.xpec.c4.game.utility.GUIDFactory;
import com.xpec.c4.game.utility.GUIDType;
import com.xpec.c4.message.MessageTypes;
import com.xpec.c4.service.contexts.Contexts;
import com.xpec.c4.service.message.MessageAction;
import com.xpec.c4.service.module.common.PlayerCommonInfoManager;

public class ItemTreasureBox extends ItemBasic {
	
	/** 升級寶箱 */
	public static byte TYPE_LEVEL = 1;
	
	public static byte TYPE_RECYCLE = 2;
	
	public static byte TYPE_NORMAL = 3;

	/** 固定道具列表 */
	private ArrayList<ItemJsonContent> fixItemList;
	
	/** 超過設定的 vip 等級，可以額外獲得的物品*/
	private int extraGetVipLevel;
	
	/** 到達 extraGetVipLevel ， 可以額外獲得的物品*/
	private ArrayList<ItemJsonContent> vipExtraGetItemList;
	
	/** 寶箱類型 */
	private byte treasureBoxType;

	public ArrayList<ItemJsonContent> getFixItemList() {
		return fixItemList;
	}

	public void setFixItemList(ArrayList<ItemJsonContent> fixItemList) {
		this.fixItemList = fixItemList;
	}

	public byte getTreasureBoxType() {
		return treasureBoxType;
	}

	public void setTreasureBoxType(byte treasureBoxType) {
		this.treasureBoxType = treasureBoxType;
	}

	public ArrayList<ItemJsonContent> getVipExtraGetItemList() {
		return vipExtraGetItemList;
	}

	public int getExtraGetVipLevel() {
		return extraGetVipLevel;
	}

	public void setExtraGetVipLevel(int extraGetVipLevel) {
		this.extraGetVipLevel = extraGetVipLevel;
	}

	public void setVipExtraGetItemList(ArrayList<ItemJsonContent> vipExtraGetItemList) {
		this.vipExtraGetItemList = vipExtraGetItemList;
	}

	
	public static void main(String[] args) {
		
		 System.setProperty("log4j.configurationFile", "./config/log4j2.xml");
		 InitData.initAll();
		 GUIDFactory.setWorldId(1);
		 GUIDFactory.setProcessId(1);
		
		Session logSession = HibernateLogManager.txBegin();
		Session session = HibernateManager.getSession();
		Query query = session.createQuery("From PlayerModel Where userType = 0");
		ArrayList<PlayerModel> models = (ArrayList<PlayerModel>) query.list();
		HibernateManager.endSession();
		
		int count = 0;
		String itemId = "TREASURE_BOX_LEVEL_LV1";
		String defaultItemId = "TREASURE_BOX";
		
		try{
			for (PlayerModel playerModel : models) {
				if(count == 0){
					session = HibernateManager.txBegin();
					logSession =  HibernateLogManager.txBegin();
				}
				
				Player player = DataTransfer.transfer(playerModel);
				
				//item
				PlayerItemModel itemModel = new PlayerItemModel();
				itemModel.setBasicItemId(defaultItemId);
				itemModel.setItemId(itemId);
				itemModel.setCount(1);
				itemModel.setOwnerId(player.getGuid().toString());
				itemModel.setRefineEndTime(0);
				itemModel.setRefineLevel(0);
				itemModel.setStatus(ItemStatus.NORMAL.getId());
				itemModel.setExpireTime(0);
				GUID sn = GUIDFactory.createUUID(GUIDType.TYPE_ITEM);
				itemModel.setSn(sn.toString());
				session.save(itemModel);
				
				//log
				PlayerItemChangeLogModel logModel = new PlayerItemChangeLogModel();
				GUID orderId = GUIDFactory.createUUID(GUIDType.TYPE_USE_ITEM);
				logModel.setOrderId(orderId.toString());
				logModel.setAccountId(player.getAccountId().toString());
				logModel.setAfterChange(1);
				logModel.setChangeCount(1);
				logModel.setBeforeChange(0);
				logModel.setChangeWay(ItemChangeWay.ADD_BY_GMTOOL.getId());
				logModel.setChangeWayDesc(ItemChangeWay.ADD_BY_GMTOOL.toString());
				logModel.setItemId(itemId);
				logModel.setItemName("木箱1等");
				logModel.setItemSn(sn.toString());
				logModel.setPlayerId(player.getGuid().toString());
				logModel.setPlayerName(player.getNameWithNumber());
				logModel.setUserType(player.getUserType());
				logModel.setRefineLevel(0);
				logSession.save(logModel);	
				
				count ++;
				
				if(count == 200){
					HibernateManager.txCommit();
					HibernateLogManager.txCommit();
					count = 0;
				}
			}
		}catch(Exception e){
			HibernateManager.txRollback();
			HibernateLogManager.txRollback();
			return;
		}
		
		if(count > 0){
			HibernateManager.txCommit();
			HibernateLogManager.txCommit();
		}

		HibernateManager.endSession();
		HibernateLogManager.endSession();
		
		//分析
		Session analysisSession = HibernateAnalysisManager.txBegin(); 
		ItemChangeCountModel itemChangeCountModel = new ItemChangeCountModel();
		itemChangeCountModel.setCount(models.size());
		itemChangeCountModel.setItemID(itemId);
		itemChangeCountModel.setItemChangeWay(ItemChangeWay.ADD_BY_GMTOOL.toString());
		itemChangeCountModel.setRefineLevel(0);
		itemChangeCountModel.setItemCountWay(ItemCountWay.CREATE.toString());
		itemChangeCountModel.setItemName("木箱1等");
		analysisSession.save(itemChangeCountModel);
		HibernateAnalysisManager.txCommitFailRollbackClearSession();
	}
	
	@Override
	public int use(Player player, Item useItem, int useCount, GUID targetGuid, Object... object) {
		return 0;
	}

	private void addItem(ChangeItemLister itemLister, ArrayList<ItemJsonContent> itemInfos,ArrayList<TreasureBoxChangeLogModel> logList, boolean fromVip) {
		TreasureBoxChangeLogModel log = null;
		for (ItemJsonContent content : itemInfos) {
			log = new TreasureBoxChangeLogModel();
			log.setExtraItem(fromVip);
			log.setCount(content.getCount());
			log.setItemId(content.getItemId());
			log.setTreasureBoxId(this.getItemId());
			logList.add(log);
			itemLister.addItem(null, content.getItemId(), content.getCount(), this.getItemRefineLevel());
		}
	}
	
	@Override
	public int applyItemToDc(BasicZoneModule zoneModule, Player player, Item useItem, GUID orderId, Object... object) {
		ArrayList<TreasureBoxChangeLogModel> loglist = new ArrayList<TreasureBoxChangeLogModel>();

		int levelBoxLevel = 0;
		if(treasureBoxType == TYPE_LEVEL || treasureBoxType == TYPE_RECYCLE){ 
			//如果是 等級寶箱 或是 循環寶箱 要更新角色身上 lastLevelBoxLevel 
			levelBoxLevel = treasureBoxType == TYPE_RECYCLE ? useItem.getExtraSetting().getUseLevel() : getUseLevel();
			player.setLastLevelBoxUseLevel(levelBoxLevel);
			
			//去DC更新數值
			UpdateLastLevelBoxUseLevelAsync async = new UpdateLastLevelBoxUseLevelAsync();
			async.key = player.getGuid();
			async.setPlayerId(player.getGuid());
			async.setLevelBoxLevel(levelBoxLevel);
			zoneModule.addCentralAsyncCommand(async);
		} else {
			levelBoxLevel = getUseLevel();
		}
		
		ChangeItemLister itemLister = new ChangeItemLister();
		addItem(itemLister, fixItemList, loglist, false);
		
		if (player.isPurchaseMember() && player.getVip() >= extraGetVipLevel) { //如果vip > 0 ，要給他對應等級的獎勵
			if(vipExtraGetItemList != null && vipExtraGetItemList.size() > 0){
				addItem(itemLister, vipExtraGetItemList, loglist, true);
			}
		}
		
		zoneModule.getPlayerDataAgent().updatePlayerItemToDC(
				orderId, player, null, itemLister, ItemChangeWay.ADD_OPEN_LEVEL_BOX, player.getZoneId(), "", null, ItemChangeParam.NO_EXP, this, "updatePlayerItemToDCBack",player.getGuid(), player.getAccountId(),useItem);
		
		for (TreasureBoxChangeLogModel log : loglist) { //寫LOG
			log.setGameId(player.getZoneId());
			log.setPlayerName(player.getNameWithNumber());
			log.setGuid(player.getGuid().toString());
			log.setOrderId(orderId.toString());
			log.setPlayerLevel(player.getLevel());
			log.setPlayerVipLevel(player.getVip());
			if (treasureBoxType == TYPE_LEVEL || treasureBoxType == TYPE_RECYCLE) {
				log.setLastTreasureBoxLevel(player.getLastLevelBoxUseLevel());
			}
			log.setThisTreasureBoxLevel(levelBoxLevel);
			zoneModule.saveDbLog(log);
		}
		
		return ErrorCode.SUCCESS;
	}
	
	public void updatePlayerItemToDCBack(BaseDataInfo obj, Object... userObject) {
		
		GUID playerId = (GUID)userObject[0];
		GUID accountId = (GUID)userObject[1];
		
		GUID sessionId = PlayerCommonInfoManager.getInstance().getSessionByPlayerGuid(playerId);
		if(sessionId == null){ //離線
			return;
		}
		
		BasicZoneModule zoneModule = (BasicZoneModule)Contexts.getModule();
		BasicZone basicZone = zoneModule.getZone();
		if(basicZone == null){
			return;
		}
		
		Player player = basicZone.getPlayer(playerId);
		if(player == null){
			return;
		}
		
		//移除blockList
		basicZone.removeBlockList(playerId, null);
		
		if (obj.getResultCode() == ErrorCode.SUCCESS) {// 成功			
			
			//把這次開的寶箱等級更新回zone上player
			if (treasureBoxType == TYPE_LEVEL || treasureBoxType == TYPE_RECYCLE) {
				Item uselevelBox = (Item) userObject[2];
				int levelBoxLevel = treasureBoxType == 2 ? uselevelBox.getExtraSetting().getUseLevel() : getUseLevel();
				player.setLastLevelBoxUseLevel(levelBoxLevel);
			}
			
			ArrayList<SSimpleItem> simpleItems = new ArrayList<SSimpleItem>();
			ItemChangeParam param = (ItemChangeParam) obj.getData();
			ChangeItemLister itemLister = param.getChangeItemLister();
			for (ChangeItem items : itemLister.getItemMap().values()) {
				simpleItems.add(items.toItem().toClientFormat());
			}

			SBroadCastGetItems broadcast = new SBroadCastGetItems();
			broadcast.setErrorCode(ErrorCode.SUCCESS);
			broadcast.setItems(simpleItems);

			MessageAction.sendMessage(sessionId, MessageTypes.S_ITEM_BROADCAST_GET_ITEMS, broadcast);
		}
		
		ItemBox.sendUseItemResponseToClient(sessionId, obj.getResultCode(), accountId, playerId);
	}

}
